﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.Global;
using CE.Database;
using CE.UserAccess;

public partial class admin_crm_agent_leads_assign : System.Web.UI.Page
{
    string PageCode = "GGRPTRADBRLEAD";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/ManagementSecureLogin.aspx");
        }
        if (!IsPostBack)
        {
            ddlLeadLimit.Items.Clear();
            ddlLeadLimit.Items.Add(new ListItem("Select", "-1"));
            for (int _lead = 1; 15 >= _lead; _lead++)
            {
                ddlLeadLimit.Items.Add(new ListItem(_lead.ToString(), _lead.ToString()));
            }
            ClearProcess();

            if (Convert.ToInt64(Session[General.UserId].ToString()) != 1)
            {
                CheckPageAccess();
            }            
            LoadBrokerList();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                if (Convert.ToInt32(txtAgentType.Text) > 0)
                {
                    string NewLeads = "1";
                    string OldLeads = "1";
                    string CheckActivity = "0";
                    string IsTesting = "0";
                    //if (ddlLeadType.Text == "1")
                    //{
                    //    NewLeads = "1";
                    //    OldLeads = "1";
                    //}
                    //else if (ddlLeadType.Text == "2")
                    //{
                    //    NewLeads = "1";
                    //    OldLeads = "0";
                    //}
                    //else if (ddlLeadType.Text == "3")
                    //{
                    //    NewLeads = "0";
                    //    OldLeads = "1";
                    //}
                    MyDatabase _myDB = new MyDatabase("GGR_DBConnectionString");
                    Int32 _result = 0;
                    string _spName = "sprocCXCRMAutoLeadAssignment";
                    SortedList _sPara = new SortedList();
                    #region Parameter
                    _sPara.Add("@_AgentId", ddlUser.Text);
                    _sPara.Add("@_AgentType", txtAgentType.Text);
                    _sPara.Add("@_LeadLimit", ddlLeadLimit.Text);
                    _sPara.Add("@_DateToDelete", txtDateToDelete.Text);
                    _sPara.Add("@_ONJPercentage", txtONJPercentage.Text);
                    _sPara.Add("@_CheckActivity", CheckActivity.ToString());
                    _sPara.Add("@_IsRunNewLead", NewLeads.ToString());
                    _sPara.Add("@_IsRunUnContactedLead", NewLeads.ToString());
                    _sPara.Add("@_IsRunOLDLead", OldLeads.ToString());
                    _sPara.Add("@_IsTesting", IsTesting.ToString());
                    #endregion

                    _myDB.ExecuteSP(_spName, _sPara);

                    string _strSelect = "";
                    DataTable _dtSelect = new DataTable();
                    _strSelect = @"SELECT COUNT(AgentLeadId) AvailableLeads FROM tblCXCRMAgentLeads WHERE [Status] = 1 ";
                    _strSelect += " AND AgentId = " + ddlUser.Text;
                    _dtSelect = _myDB.GetDataTable(_strSelect);
                    if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                    {
                        if(!Int32.TryParse(_dtSelect.Rows[0]["AvailableLeads"].ToString(), out _result))
                        {
                            _result = 0;
                        }
                    }
                    #region Log
                    Int64 _Logresult = 0;
                    MyDatabase _myLogDB = new MyDatabase("GGR_DB_ReportConnectionString");
                    string _spLogName = "sprocBrokerLeadAssignLogInsertUpdateSingleItem";
                    SortedList _sLogPara = new SortedList();
                    #region Parameter
                    _sLogPara.Add("@UserId", Session[General.UserId].ToString());
                    _sLogPara.Add("@AgentId", ddlUser.Text);
                    _sLogPara.Add("@AgentType", txtAgentType.Text);
                    _sLogPara.Add("@LeadLimit", ddlLeadLimit.Text);
                    _sLogPara.Add("@DateToDelete", txtDateToDelete.Text);
                    _sLogPara.Add("@ONJPercentage", txtONJPercentage.Text);
                    _sLogPara.Add("@CheckActivity", CheckActivity.ToString());
                    _sLogPara.Add("@IsRunNewLead", NewLeads.ToString());
                    _sLogPara.Add("@IsRunUnContactedLead", NewLeads.ToString());
                    _sLogPara.Add("@IsRunOLDLead", OldLeads.ToString());
                    _sLogPara.Add("@IsTesting", IsTesting.ToString());
                    _sLogPara.Add("@AssignLeads", _result.ToString());
                    if (_result > 0)
                    {
                        _sLogPara.Add("@AssignStatus", 1);
                        _sLogPara.Add("@Message", "Successfully (" + _result.ToString() + " Leads) Assigned!. Please click VIEW Button to Close.");
                    }
                    else
                    {
                        _sLogPara.Add("@AssignStatus", 0);
                        _sLogPara.Add("@Message", "Lead Not Assigned!.");
                    }
                    #endregion

                    _Logresult = _myLogDB.ExecuteSP(_spLogName, _sLogPara);
                    #endregion

                    if (_result > 0)
                    {
                        btnClear_Click(null, null);
                        pnlMessage.Visible = true;
                        pnlBroker.Visible = false;
                        lblError.Text = "";

                        _strSelect = "";
                        _strSelect = @"EXEC [sprocReportsAgentLeadAssignLogInsertSelectItemList] ";
                        _myDB.ExecuteNonSqlStatement(_strSelect);

                        lblLeadMessage.Text = "Successfully (" + _result.ToString() + " Leads) Assigned!. Please click VIEW Button to Close.";
                    }
                    else
                    {
                        lblError.Text = "Lead Not Assigned!.";
                        lblLeadMessage.Text = "";
                    }

                    #region SQL Query
                    // MyDatabase _myDB = new MyDatabase("GGR_DBConnectionString");
                    //string _strUpdateSQL = "EXEC [sprocCXCRMAutoLeadAssignment] ";
                    //_strUpdateSQL += "@_AgentId = " + ddlUser.Text + ", ";
                    //_strUpdateSQL += "@_AgentType = " + txtAgentType.Text + ", ";
                    //_strUpdateSQL += "@_LeadLimit = " + txtLeadLimit.Text + ", ";
                    //_strUpdateSQL += "@_DateToDelete = " + txtDateToDelete.Text + ", ";
                    //_strUpdateSQL += "@_ONJPercentage = " + txtONJPercentage.Text + ", ";
                    //_strUpdateSQL += "@_CheckActivity = " + txtCheckActivity.Text + ", ";
                    //_strUpdateSQL += "@_IsRunNewLead = " + txtIsRunNewLead.Text + ", ";
                    //_strUpdateSQL += "@_IsRunUnContactedLead = " + txtIsRunUnContactedLead.Text + ", ";
                    //_strUpdateSQL += "@_IsRunOLDLead = " + txtIsRunOLDLead.Text + ", ";
                    //_strUpdateSQL += "@_IsTesting = " + txtIsTesting.Text;

                    //object _retValue = _myDB.ExecuteScalarSqlStatement(_strUpdateSQL);
                    //if (_retValue != null)
                    //{
                        //btnClear_Click(null, null);
                        //pnlMessage.Visible = true;
                        //pnlBroker.Visible = false;
                        //lblError.Text = "";
                        //lblLeadMessage.Text = "Successfully Leads Assigned!. Please click VIEW Button, Then select Broker and check Available Leads.";
                    //}
                    //else
                    //{
                    //    lblError.Text = "Leads Assign Faild!.";
                    //    lblLeadMessage.Text = "";
                    //}
                    #endregion
                }
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message.ToString();
        }
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        ddlUser.SelectedIndex = 0;
        ClearProcess();
    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        pnlMessage.Visible = false;
        pnlBroker.Visible = true;
    }
    
    protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlLeadLimit.Text = "-1";
        ddlBrokerLevel.Text = "-1";        
        //ddlLeadType.Text = "-1";
        ddlBrokerLevel_SelectedIndexChanged(null, null);
        LoadBroker();
    }

    protected void ddlBrokerLevel_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBrokerLevel.Text == "ONF")
        {
           //ddlLeadType.Text = "3";
            //ddlLeadType.Enabled = false;
        }
        else
        {
            //ddlLeadType.Text = "-1";
            //ddlLeadType.Enabled = true;
        }
    }

    private void ClearProcess()
    {
        lblError.Text = "";
        lblLeadMessage.Text = "";
        txtEmail.Text = "";
        txtTHName.Text = "";
        txtENName.Text = "";
        txtNickName.Text = "";
        ddlBrokerLevel.Text = "-1";
        ddlBrokerLevel_SelectedIndexChanged(null, null);
        txtAgentType.Text = "-1";
        txtFreshLeadLimit.Text = "0";
        txtUncontactLeadLimit.Text = "0";
        txtLastYearLeadLimit.Text = "0";
        txtDateToDelete.Text = "6";
        txtONJPercentage.Text = "35";
        txtCheckActivity.Text = "0";
        txtIsRunNewLead.Text = "0";
        txtIsRunUnContactedLead.Text = "0";
        txtIsRunOLDLead.Text = "0";
        txtIsTesting.Text = "0";
        txtAvailableLeads.Text = "0";
        ddlLeadLimit.Text = "-1";
        //ddlLeadType.Text = "-1";
        //ddlLeadType.Enabled = true;
    }

    private void LoadBrokerList()
    {
        ddlUser.Items.Clear();
        MyDatabase _db = new MyDatabase("GGR_DBConnectionString");
        DataSet _dsUserList = new DataSet();
        DataTable _dtUser = new DataTable();
        SortedList _sPara = new SortedList();
        _sPara.Add("@BrokerId", 0);
        _sPara.Add("@Status", 1);
        _dsUserList = _db.GetDataSet("sprocCXCRMBrokerDetailsSelectItemList", _sPara);
        if (_dsUserList != null && _dsUserList.Tables.Count > 0)
        {
            _dtUser = _dsUserList.Tables[0];
        }
        if (_dtUser != null && _dtUser.Rows.Count > 0)
        {
            for (int i = 0; i < _dtUser.Rows.Count; i++)
            {
                ddlUser.Items.Add(new ListItem(_dtUser.Rows[i]["BrokerCode"].ToString(), _dtUser.Rows[i]["CEID"].ToString()));
            }
            ddlUser.Items.Insert(0, new ListItem("Select", "-1"));
        }
        else
        {
            ddlUser.Items.Clear();
            ddlUser.Items.Insert(0, new ListItem("None", "-1"));
        }
    }

    public void LoadBroker()
    {
        lblError.Text = "";
        MyDatabase _db = new MyDatabase("GGR_DBConnectionString");
        DataSet _dsUserList = new DataSet();
        DataTable _dtUser = new DataTable();
        SortedList _sPara = new SortedList();
        _sPara.Add("@BrokerId", Convert.ToInt64(ddlUser.Text));
        _sPara.Add("@Status", 1);
        _dsUserList = _db.GetDataSet("sprocCXCRMBrokerDetailsSelectItemList", _sPara);
        if (_dsUserList != null && _dsUserList.Tables.Count > 0)
        {
            _dtUser = _dsUserList.Tables[0];
        }
        if (_dtUser != null && _dtUser.Rows.Count > 0)
        {
            txtEmail.Text = _dtUser.Rows[0]["Email"].ToString();
            txtTHName.Text = _dtUser.Rows[0]["THName"].ToString();
            txtENName.Text = _dtUser.Rows[0]["ENName"].ToString();
            txtNickName.Text = _dtUser.Rows[0]["NickName"].ToString();
            txtNickName.Text = _dtUser.Rows[0]["NickName"].ToString();
            ddlBrokerLevel.Text = _dtUser.Rows[0]["BrokerLevel"].ToString();
            ddlBrokerLevel_SelectedIndexChanged(null, null);
            txtAgentType.Text = _dtUser.Rows[0]["AgentType"].ToString();
            txtFreshLeadLimit.Text = _dtUser.Rows[0]["FreshLeadLimit"].ToString();
            txtUncontactLeadLimit.Text = _dtUser.Rows[0]["UncontactLeadLimit"].ToString();
            txtLastYearLeadLimit.Text = _dtUser.Rows[0]["LastYearLeadLimit"].ToString();
            txtDateToDelete.Text = _dtUser.Rows[0]["DateToDelete"].ToString();
            txtONJPercentage.Text = _dtUser.Rows[0]["ONJPercentage"].ToString();
            txtCheckActivity.Text = _dtUser.Rows[0]["CheckActivity"].ToString();
            txtIsRunNewLead.Text = _dtUser.Rows[0]["IsRunNewLead"].ToString();
            txtIsRunUnContactedLead.Text = _dtUser.Rows[0]["IsRunUnContactedLead"].ToString();
            txtIsRunOLDLead.Text = _dtUser.Rows[0]["IsRunOLDLead"].ToString();
            txtIsTesting.Text = _dtUser.Rows[0]["IsTesting"].ToString();
            if (_dsUserList.Tables.Count > 1 && _dsUserList.Tables[1].Rows.Count > 0)
            {
                txtAvailableLeads.Text = _dsUserList.Tables[1].Rows[0]["AvailableLeads"].ToString();
            }
        }
        else
        {
            txtEmail.Text = "";
            txtTHName.Text = "";
            txtENName.Text = "";
            txtNickName.Text = "";
            ddlBrokerLevel.Text = "-1";
            ddlBrokerLevel_SelectedIndexChanged(null, null);
            txtAgentType.Text = "-1";
            txtFreshLeadLimit.Text = "0";
            txtUncontactLeadLimit.Text = "0";
            txtLastYearLeadLimit.Text = "0";
            txtDateToDelete.Text = "6";
            txtONJPercentage.Text = "35";
            txtCheckActivity.Text = "0";
            txtIsRunNewLead.Text = "0";
            txtIsRunUnContactedLead.Text = "0";
            txtIsRunOLDLead.Text = "0";
            txtIsTesting.Text = "0";
            txtAvailableLeads.Text = "0";
            ddlLeadLimit.Text = "-1";
            //ddlLeadType.Text = "-1";
            //ddlLeadType.Enabled = true;
        }
    }

    private void CheckPageAccess()
    {
        Int64 PageAccess = General.GetPageAccess(Convert.ToInt64(Session[General.UserId].ToString()), PageCode);
        if (PageAccess == 0)
        {
            Response.Redirect("~/UserMessage.aspx?menu=0&mt=UM&ec=101");
        }
        else if (PageAccess > 0)
        {
            EnablePageAccess(PageAccess);
        }
    }

    private void EnablePageAccess(Int64 PageAccess)
    {
        if (PageAccess == 100)
        {
            btnSubmit.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            btnSubmit.Enabled = true;
        }
    }

}
